﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Hands.Queue
{
    public class AtomicInteger : Atomic<int>
    {
        public AtomicInteger(int value)
            : base(value)
        { }

        public override bool compareAndSet(int current, int next)
        {
            return Interlocked.CompareExchange(ref value, next, current) == current;
        }

        public void addAndSet(int addend)
        {
            int newValue;
            int currentValue;
            do
            {
                currentValue = value;
                newValue = value + addend;
                if (compareAndSet(currentValue, newValue))
                {
                    break;
                }
            }
            while (true);
        }

        public void subtractAndSet(int subtrahend)
        {
            int newValue;
            int currentValue;
            do
            {
                currentValue = value;
                newValue = value - subtrahend;
                if (compareAndSet(currentValue, newValue))
                    break;

            }
            while (true);
        }

    }
}
